package com.stars.easyms.feign.autoconfigure;

import com.netflix.config.ConfigurationManager;
import com.stars.easyms.base.util.FastJsonUtil;
import com.stars.easyms.feign.plugin.EasyMsFeignPluginRegister;
import com.stars.easyms.feign.properties.EasyMsFeignProperties;
import com.stars.easyms.feign.request.EasyMsFeignRequestInterceptor;
import com.stars.easyms.feign.response.EasyMsFeignDecoder;
import com.stars.easyms.feign.request.EasyMsFeignEncoder;
import feign.RequestInterceptor;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.optionals.OptionalDecoder;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

/**
 * Feign自动配置类，为feign增加request拦截配置
 *
 * @author guoguifang
 * @date 2020-08-15 10:12
 * @since 1.6.1
 */
@Configuration
@EnableConfigurationProperties(EasyMsFeignProperties.class)
public class EasyMsFeignAutoConfiguration implements InitializingBean {

    private ObjectFactory<HttpMessageConverters> messageConverters;

    public EasyMsFeignAutoConfiguration(ObjectFactory<HttpMessageConverters> messageConverters) {
        this.messageConverters = messageConverters;
        ConfigurationManager.getConfigInstance().setProperty("ribbon.ConnectTimeout", 3000L);
        ConfigurationManager.getConfigInstance().setProperty("ribbon.ReadTimeout", 5000L);
    }

    @Bean
    public RequestInterceptor easyMsFeignRequestInterceptor() {
        return new EasyMsFeignRequestInterceptor();
    }

    @Bean
    @Primary
    public Encoder easyMsFeignEncoder() {
        return new EasyMsFeignEncoder(new SpringEncoder(feignHttpMessageConverter()));
    }

    @Bean
    @Primary
    public Decoder easyMsFeignDecoder() {
        return new OptionalDecoder(new EasyMsFeignDecoder(
                new SpringDecoder(feignHttpMessageConverter()), new SpringDecoder(this.messageConverters)));
    }

    private ObjectFactory<HttpMessageConverters> feignHttpMessageConverter() {
        return () -> new HttpMessageConverters(FastJsonUtil.getFastJsonHttpMessageConverter());
    }

    @Override
    public void afterPropertiesSet() {
        EasyMsFeignPluginRegister.init();
    }
}
